package cn.cnsuh.service.impl;


import cn.cnsuh.dao.UserDao;
import cn.cnsuh.dao.impl.UserDaoImpl;
import cn.cnsuh.domain.User;
import cn.cnsuh.service.UserService;
import cn.cnsuh.util.MailUtils2;
import cn.cnsuh.util.UuidUtil;

import java.util.List;

/**
 * @author Magic
 * @create 2020-05-09 11:28
 */
public class UserServiceImpl implements UserService {
    private UserDao userDao = new UserDaoImpl();

    /**
     * 登录方法
     *
     * @param user
     * @return
     */
    @Override
    public User login(User user) {
        return userDao.findByUsernameAndPassword(user.getUsername(), user.getPassword());
    }


    /**
     * 注册用户
     *
     * @param user
     * @return
     */
    @Override
    public boolean regist(User user) throws Exception {
        //1.根据用户名查询用户对象
        User u = userDao.findByUsername(user.getUsername());
        //判断u是否为null
        if (u != null) {
            //用户已经存在
            return false;
        }

        //2.保存用户信息
        //2.1设置激活码，唯一字符串
        user.setCode(UuidUtil.getUuid());
        //2.2设置激活状态
        user.setStatus("N");
        userDao.save(user);

        //3.激活邮件发送，正文？
        String call = "";
        if ("male".equals(user.getSex())) {
            call = "先生";
        } else {
            call = "师姐";
        }
//        String content = user.getRealname() + call + "你好" +
//                "<a href='http://112.74.86.148:8080/0x3f3f3f3f/user/active?code=" + user.getCode() + "'>点击激活【0x3f3f3f3f网】</a> <br>" +
//                "或者访问以下链接：http://112.74.86.148:8080/0x3f3f3f3f/user/active?code=" + user.getCode();
        String content = user.getRealname() + call + "你好" +
                "<a href='http://127.0.0.1:8080/demo/user/active?code=" + user.getCode() + "'>点击激活【0x3f3f3f3f网】</a> <br>" +
                "或者访问以下链接：http://127.0.0.1:8080/gameweb/user/active?code=" + user.getCode();

//        MailUtils.sendMail(user.getEmail(), content, "激活邮件");
        MailUtils2.sendMail(user.getEmail(), "这是一封激活邮件", content);


        return true;
    }


    /**
     * 激活用户
     *
     * @param code
     * @return
     */
    @Override
    public boolean active(String code) {
        //1.根据激活码查询用户对象
        User user = userDao.findByCode(code);
        if (user != null) {
            //2.调用dao的修改激活状态的方法
            userDao.updateStatus(user);
            return true;
        } else {
            return false;
        }


    }

    @Override
    public boolean updateUser(User user, int uid) {
        if (userDao.findByUsername(user.getUsername()) == null) {

            userDao.updateU(user, uid);
            return true;
        } else {
            return false;
        }

    }

    @Override
    public List<User> findAll() {
        //调用Dao完成查询
        return userDao.findAll();
    }

    @Override
    public void deleteUser(int uid) {
        userDao.delete(uid);
    }
}
